package com.zmn.oms.third.pinduoduo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.dubbo.interfaces.channel.product.third.ChannelProductThirdListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.oms.business.interfaces.baidumap.BaiduMapBService;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.business.interfaces.third.PinDuoDuoSignShopService;
import com.zmn.oms.business.interfaces.track.OrderTrackBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.exception.chan.ChannelFacadeException;
import com.zmn.oms.model.dto.baidumap.LngLatLocation;
import com.zmn.oms.model.dto.order.proxy.CancelOrderDTO;
import com.zmn.oms.model.dto.order.proxy.CreateOrderDTO;
import com.zmn.oms.model.dto.order.proxy.OrderLogDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.entity.chan.OrderClue;
import com.zmn.oms.model.entity.changerecord.OrderChangeRecord;
import com.zmn.oms.model.entity.third.PinDuoDuoSignShop;
import com.zmn.oms.model.entity.track.OrderTrackQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.core.interfaces.ChannelFacadeBService;
import com.zmn.oms.third.pinduoduo.PinDuoDuoApiInvoker;
import com.zmn.oms.third.pinduoduo.PinDuoDuoConsts;
import com.zmn.oms.third.pinduoduo.PinDuoDuoMapper;
import com.zmn.oms.third.pinduoduo.dto.PinDuoDuoAcceptOrderDTO;
import com.zmn.oms.third.pinduoduo.dto.api.*;
import com.zmn.oms.third.pinduoduo.service.PinDuoDuoBService;
import com.zmn.oms.zmn.business.interfaces.proxy.ProxyOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import io.shardingsphere.core.keygen.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2021/01/05 15:54
 */
@Slf4j
@Service("pinDuoDuoBService")
public class PinDuoDuoBServiceImpl implements PinDuoDuoBService {

//    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
//    private FactoryApplyModifyRemoteService factoryApplyModifyRemoteService;
//    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
//    private DocumentaryContentListRemoteService documentaryContentListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ChannelProductThirdListRemoteService channelProductThirdListRemoteService;
    @Autowired
    private PinDuoDuoSignShopService pinDuoDuoSignShopService;
    @Autowired
    private ChannelFacadeBService channelFacadeBService;
    @Autowired
    private ProxyOrderBService proxyOrderBService;
    @Autowired
    private BaiduMapBService baiduMapBService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private DefaultKeyGenerator defaultKeyGenerator;
    @Autowired
    private OrderRemarkBService orderRemarkBService;
    @Autowired
    private OrderTrackBService orderTrackBService;
    @Autowired
    private OrderChangeRecordService orderChangeRecordService;

    @Override
    public void createOrder(OrderClue orderClue, String params) throws ChannelFacadeException {
        PinDuoDuoCreateOrderParam pddOrderParams = null;
        try {
            pddOrderParams = JSONObject.parseObject(params, PinDuoDuoCreateOrderParam.class);
        } catch (Exception e) {
            log.error(String.format("【%s】解析订单数据失败:%s，params=[%s]", PinDuoDuoConsts.CHANNEL_NAME,
                    e.getMessage(), params), e);
            // 不再重试
            throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "解析订单数据失败", e);
        }

        CreateOrderDTO zmnOrder = null;
        try {
            // 生成创建订单的数据
            zmnOrder = this.buildZmnOrder(pddOrderParams);
            // 补充信息
            zmnOrder.setOrderClueId(orderClue.getId());

            // 查找店铺是否签约
            Long mallId = pddOrderParams.getMallId();
            PinDuoDuoSignShop pddSignShop = pinDuoDuoSignShopService.findPinDuoDuoSignShopByMallId(mallId);
            if (Objects.isNull(pddSignShop) || pddSignShop.getSignStatus() != 1) {
                log.warn("【{}】保存订单失败：店铺未申请签约，PinDuoDuoSignShop=[{}]", PinDuoDuoConsts.CHANNEL_NAME,
                        JSON.toJSONString(pddSignShop));
                proxyOrderBService.saveAsOrderClueDetail(zmnOrder, "店铺未申请签约");
                throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "店铺未申请签约");
            }

            zmnOrder.setChannelId(pddSignShop.getChannelId());
            proxyOrderBService.createOrder(zmnOrder);
        } catch (ChannelFacadeException e) {
            throw e;
        } catch (Exception e) {
            log.error(String.format("【%s】保存订单失败:%s，CreateOrderDTO=[%s]", PinDuoDuoConsts.CHANNEL_NAME,
                    e.getMessage(), JSON.toJSONString(zmnOrder)));

            if (e instanceof OmsBaseException && e.getMessage().contains("余额不足")) {
                // 余额不足，不再重试
                throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_SERVER_UNKNOWN, "厂商账户余额不足");
            }
            else {
                // 稍后重试
                throw new ChannelFacadeException(StatusConsts.STATUS_ERROR, e.getMessage(), e);
            }
        }
    }

    @Override
    public void appointOrder(OrderClue orderClue, String params) throws ChannelFacadeException {
        // 获取预约通知的具体内容
        PinDuoDuoCreateOrderParam pddOrderParams = null;
        try {
            pddOrderParams = JSONObject.parseObject(params, PinDuoDuoCreateOrderParam.class);
        } catch (Exception e) {
            log.error(String.format("【%s】解析预约通知参数失败：%s，params=[%s]", PinDuoDuoConsts.CHANNEL_NAME,
                    e.getMessage(), params), e);
            // 不再重试
            throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "解析预约通知参数失败", e);
        }

        // 查找对应的订单
        Long zmnOrderId = orderClue.getZmnOrderId();
        OrderWork dbOrderWork = orderWorkService.findOrderWorkByKey(zmnOrderId, zmnOrderId);
        if (Objects.isNull(dbOrderWork)) {
            log.warn("【{}】预约通知失败：未找到对应的订单，OrderClue=[{}], params=[{}]", PinDuoDuoConsts.CHANNEL_NAME,
                    JSON.toJSONString(orderClue), params);
            // 不再重试
            throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "未找到对应的订单");
        }

        {//将预约通知添加到操作日志“用户已签收”
            OrderLogDTO orderLogDTO = new OrderLogDTO();
            orderLogDTO.setOrderId(zmnOrderId);
            orderLogDTO.setOperatorLogRemark("用户已签收");
            channelFacadeBService.saveCustomOrderLog(orderLogDTO);
        }

        //工单自动流转
        workFlowContextBService.asyncAutoFlow(zmnOrderId, zmnOrderId);

        //如果预约通知时有预约时间，再同步一次预约时间。
        if (Objects.nonNull(dbOrderWork.getDutyTime())){
            OrderWorkLogChange orderWorkLogChange = new OrderWorkLogChange();
            orderWorkLogChange.setOuterId(dbOrderWork.getOuterId());
            orderWorkLogChange.setDutyTime(dbOrderWork.getDutyTime());
            orderWorkLogChange.setOrderId(dbOrderWork.getOrderId());
            orderWorkLogChange.setWorkId(dbOrderWork.getWorkId());
            orderWorkLogChange.setChannelId(dbOrderWork.getChannelId());
            orderWorkLogChange.setStatus(dbOrderWork.getStatus());
            orderWorkLogChange.setResultStatus(dbOrderWork.getResultStatus());
            try {
                this.sendAppointOrderToPinDuoDuo(orderWorkLogChange);
            } catch (OmsBaseException omsBaseException) {
                log.error("【{}】收到预约通知消息，同步预约时间失败！工单号：[{}]", PinDuoDuoConsts.CHANNEL_NAME,
                        dbOrderWork.getWorkId());
            }
        }

        // 自动跟单
        this.autoOrderTrack(dbOrderWork);
    }

    @Override
    public void cancelOrder(OrderClue orderClue, String params) throws ChannelFacadeException {
        // 获取取消订单的具体内容
        PinDuoDuoCancelOrderParam paramCancelOrder = null;
        try {
            paramCancelOrder = JSONObject.parseObject(params, PinDuoDuoCancelOrderParam.class);
        } catch (Exception e) {
            log.error(String.format("【%s】解析取消订单参数失败：%s，params=[%s]", PinDuoDuoConsts.CHANNEL_NAME,
                    e.getMessage(), params), e);
            // 不再重试
            throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "解析取消订单参数失败", e);
        }

        // 查找对应的订单
        Long zmnOrderId = orderClue.getZmnOrderId();
        OrderWork dbOrderWork = orderWorkService.findOrderWorkByKey(zmnOrderId, zmnOrderId);
        if (Objects.isNull(dbOrderWork)) {
            // 不再重试
            throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "未找到对应的订单");
        }

        log.info("【{}】取消订单：订单Id:[{}]，OuterId:[{}]，取消原因:[{}]，扩展信息:[{}]", PinDuoDuoConsts.CHANNEL_NAME,
                zmnOrderId, dbOrderWork.getOuterId(), paramCancelOrder.getReason(), paramCancelOrder.getAttributes());

        try {
            // 取消订单
            CancelOrderDTO cancelOrderDTO = new CancelOrderDTO();
            cancelOrderDTO.setOrderId(zmnOrderId);
            cancelOrderDTO.setOuterId(dbOrderWork.getOuterId());
            cancelOrderDTO.setChannelId(dbOrderWork.getChannelId());
            cancelOrderDTO.setOperatorId((long) dbOrderWork.getChannelId());
            cancelOrderDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_CHANNEL);
            cancelOrderDTO.setRemark(paramCancelOrder.getReason());

            proxyOrderBService.cancelOrder(cancelOrderDTO);
        } catch (OmsBaseException e) {
            log.error(String.format("【%s】取消订单失败：%s", PinDuoDuoConsts.CHANNEL_NAME, e.getMessage()), e);
            // 不再重试
            throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, e.getMessage(), e);
        }
    }

    @Override
    public void signShop(String params) throws ChannelFacadeException {
        // 获取服务签约的具体内容
        PinDuoDuoSignParam pinDuoDuoSignParam = null;
        try {
            pinDuoDuoSignParam = JSONObject.parseObject(params, PinDuoDuoSignParam.class);
        } catch (Exception e) {
            log.error(String.format("【%s】解析服务签约参数失败：%s，params=[%s]", PinDuoDuoConsts.CHANNEL_NAME,
                    e.getMessage(), params), e);
            // 不再重试
            throw new ChannelFacadeException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "解析服务签约参数失败", e);
        }

        log.info("【{}】服务签约消息！ 消息:[{}]", PinDuoDuoConsts.CHANNEL_NAME, pinDuoDuoSignParam.toString());

        Long mallId = pinDuoDuoSignParam.getMallId();
        // 签约店铺是否需要审核
        boolean isReviewRequired = true;
        PinDuoDuoSignShop pddSignShop = null;

        {// 1.将最新的 SignOrderSn 存入数据库，以便往回同步签约状态时使用

            pddSignShop = new PinDuoDuoSignShop();
            pddSignShop.setMallId(mallId);
            pddSignShop.setSignOrderSn(pinDuoDuoSignParam.getSignOrderSn());
            pddSignShop.setServType(pinDuoDuoSignParam.getServType());

            // 直接发送拒绝消息
            PinDuoDuoSendSign pinDuoDuoSendSign = new PinDuoDuoSendSign();
            pinDuoDuoSendSign.setSignOrderSn(pddSignShop.getSignOrderSn());
            pinDuoDuoSendSign.setMallId(mallId);
            pinDuoDuoSendSign.setServType(pddSignShop.getServType());
            pinDuoDuoSendSign.setVerifyStatus(PinDuoDuoConsts.PDD_SIGN_REJECT);
            String paramJson = JSON.toJSONString(pinDuoDuoSendSign, SerializerFeature.SortField.MapSortField);
            PinDuoDuoApiInvoker.doRequest(PinDuoDuoConsts.PDD_SERVICE_PATH, paramJson);

            try {
                PinDuoDuoSignShop dbPddSignShop = pinDuoDuoSignShopService.findPinDuoDuoSignShopByMallId(mallId);

                boolean isNewSignShop = Objects.isNull(dbPddSignShop);
                isReviewRequired = isNewSignShop || !Objects.equals(1, dbPddSignShop.getSignStatus());

                if (isReviewRequired) {
                    pddSignShop.setMallName(pinDuoDuoSignParam.getMallName());
                    pddSignShop.setServName(pinDuoDuoSignParam.getServName());
                    pddSignShop.setApplyTime(DateUtil.parse(pinDuoDuoSignParam.getApplyTime()));
                    if (Objects.nonNull(pinDuoDuoSignParam.getContactInfo())) {
                        pddSignShop.setContactName(pinDuoDuoSignParam.getContactInfo().getContactName());
                        pddSignShop.setMobile(pinDuoDuoSignParam.getContactInfo().getMobile());
                        pddSignShop.setTelephone(pinDuoDuoSignParam.getContactInfo().getTelephone());
                    }
                    pddSignShop.setAttributes(pinDuoDuoSignParam.getAttributes());

                    if (isNewSignShop) {
                        pddSignShop.setSignShopId(defaultKeyGenerator.generateKey().longValue());
                        pddSignShop.setCreater("系统");
                    }
                    // 如果解约或拒绝，重新进入审核状态中
                    else {
                        pddSignShop.setSignStatus(0);
                        pddSignShop.setSyncStatus(0);
                        pddSignShop.setUpdater("系统");
                    }
                }
                // 终止合作，状态全部拒绝
                pddSignShop.setSignStatus(GlobalConsts.YES);
                pddSignShop.setSyncStatus(GlobalConsts.YES);
                if (isNewSignShop) {
                    pinDuoDuoSignShopService.addPinDuoDuoSignShop(pddSignShop);
                }
                else {
                    pinDuoDuoSignShopService.modifyPinDuoDuoSignShopByMallId(pddSignShop);
                }
            } catch (Exception e) {
                log.error(String.format("【%s】保存店铺签约状态失败：%s，PinDuoDuoSignShop=[%s]", PinDuoDuoConsts.CHANNEL_NAME,
                        e.getMessage(), JSON.toJSONString(pddSignShop)), e);
                throw new ChannelFacadeException(PinDuoDuoConsts.ZMN_RETURN_CODE_SIGN_SHOP_ERROR, e.getMessage(), e);
            }
        }

        // 2.如果已签约(店铺已审核通过)，直接发送签约结果。
        /*if (!isReviewRequired){
            PinDuoDuoSendSign pinDuoDuoSendSign = new PinDuoDuoSendSign();
            pinDuoDuoSendSign.setSignOrderSn(pddSignShop.getSignOrderSn());
            pinDuoDuoSendSign.setMallId(mallId);
            pinDuoDuoSendSign.setServType(pddSignShop.getServType());
            pinDuoDuoSendSign.setVerifyStatus(PinDuoDuoConsts.PDD_SIGN_ACCEPT);
            String paramJson = JSON.toJSONString(pinDuoDuoSendSign, SerializerFeature.SortField.MapSortField);
            PinDuoDuoApiInvoker.doRequest(PinDuoDuoConsts.PDD_SERVICE_PATH, paramJson);
        }
        // 3.需要签约（包括重新签约）的店铺，则向厂商招募推送一次消息，
        else {
            try {
                FactoryMallApplyDIO factoryMallApplyDIO = BeanMapper.map(pddSignShop, FactoryMallApplyDIO.class);
                factoryMallApplyDIO.setMallName(pddSignShop.getMallName() + "（拼多多）");
                ResponseDTO responseDTO = factoryApplyModifyRemoteService.addMallApply(factoryMallApplyDIO);
                if (!responseDTO.isSuccess()) {
                    log.warn("【{}】向厂商招募推送店铺信息失败，ResponseDTO=[{}]", PinDuoDuoConsts.CHANNEL_NAME,
                            JSON.toJSONString(responseDTO));
                    throw new ChannelFacadeException(PinDuoDuoConsts.ZMN_RETURN_CODE_SIGN_SHOP_ERROR,
                            responseDTO.getMessage());
                }
            } catch (Exception e) {
                log.error(String.format("【%s】向厂商招募推送店铺信息失败：%s，PinDuoDuoSignShop=[%s]",
                        PinDuoDuoConsts.CHANNEL_NAME, e.getMessage(), JSON.toJSONString(pddSignShop)), e);
                throw new ChannelFacadeException(PinDuoDuoConsts.ZMN_RETURN_CODE_SIGN_SHOP_ERROR, e.getMessage(), e);
            }
        }*/
    }

    /**
     * 同步服务预约给拼多多服务
     * @param orderWorkLogChange
     * @return void
     * @author wangxiaokun
     */
    private void sendAppointOrderToPinDuoDuo(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException{
        // 参数判断
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException(PinDuoDuoConsts.ERROR_CODE_PARAM_INVALID, "消息通知参数为空");
        }

        //判断是否设置预约时间操作
        Date dutyTime = orderWorkLogChange.getDutyTime();
        if (Objects.isNull(dutyTime)){
            return;
        }

        String outerId = orderWorkLogChange.getOuterId();
        // 判断外部工单id
        if (Objects.isNull(outerId) || outerId.isEmpty()) {
            throw new OmsBaseException(PinDuoDuoConsts.ERROR_CODE_SERVER_UNKNOWN, "消息通知参数错误-没有对应的外部订单Id");
        }

        PinDuoDuoAcceptOrderDTO pinDuoDuoAcceptOrderDTO = new PinDuoDuoAcceptOrderDTO();
        pinDuoDuoAcceptOrderDTO.setServOrderSn(outerId);
        pinDuoDuoAcceptOrderDTO.setBizStatus(PinDuoDuoConsts.PDD_APPOINT_SERV);
        pinDuoDuoAcceptOrderDTO.setAppointServTime(DateUtil.toString(orderWorkLogChange.getDutyTime(), "yyyy-MM-dd HH:mm:ss"));
        pinDuoDuoAcceptOrderDTO.setAppointServEndTime(DateUtil.toString(orderWorkLogChange.getDutyTime(), "yyyy-MM-dd HH:mm:ss"));
        pinDuoDuoAcceptOrderDTO.setExecuteTime(DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd HH:mm:ss"));
        log.info("【{}-API】 预约通知，预约时间:[{}]", PinDuoDuoConsts.CHANNEL_NAME, DateUtil.toString(orderWorkLogChange.getDutyTime(), "yyyy-MM-dd HH:mm:ss"));

        // 是否改约
        OrderChangeRecord orderChangeRecord = orderChangeRecordService.getChangeRecordByOrderId(orderWorkLogChange.getOrderId());
        if (Objects.nonNull(orderChangeRecord)) {
            log.info("【{}-API】 预约通知，消息:[{}]", PinDuoDuoConsts.CHANNEL_NAME, orderChangeRecord.toString());
            if (orderChangeRecord.getDutyTimeModifyCount() > 0) {
                pinDuoDuoAcceptOrderDTO.setBizStatus(PinDuoDuoConsts.PDD_CHANGE_APPOINT);
                pinDuoDuoAcceptOrderDTO.setAppointServTime(DateUtil.toString(orderChangeRecord.getLastDutyTime(), "yyyy-MM-dd HH:mm:ss"));
                pinDuoDuoAcceptOrderDTO.setAppointServEndTime(DateUtil.toString(orderChangeRecord.getLastDutyTime(), "yyyy-MM-dd HH:mm:ss"));
            }
        }

        // 发送http请求
        String paramJson = JSON.toJSONString(pinDuoDuoAcceptOrderDTO, SerializerFeature.SortField.MapSortField);
        PinDuoDuoResponse responseRequest = PinDuoDuoApiInvoker.doRequest(PinDuoDuoConsts.PDD_SERVICE_PATH, paramJson);
        if (Objects.isNull(responseRequest) || responseRequest.getErrorCode() != PinDuoDuoConsts.PDD_RETURN_CODE_SUCCESS) {
            throw new OmsBaseException(PinDuoDuoConsts.ERROR_CODE_SEND_REQUEST_FAILED, "同步服务预约消息失败");
        }

        channelFacadeBService.saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CONFIRM, responseRequest);
    }

    /**
     * 提取拼多多订单信息，构建成啄木鸟录单对象
     * @param pddOrderParam
     * @return
     */
    private CreateOrderDTO buildZmnOrder(PinDuoDuoCreateOrderParam pddOrderParam) {
        CreateOrderDTO zmnOrder = new CreateOrderDTO();
        // 日志信息
        StringBuilder logBuilder = new StringBuilder();
        logBuilder.append("拼多多服务单号：").append(pddOrderParam.getServOrderSn())
                .append("，快递单号：").append(pddOrderParam.getMailNo())
                .append("，模版报价：").append(MoneyUtil.parseToYuan(pddOrderParam.getTplPrice()))
                .append("元（此价格仅供参考，非最终成交价格）")
                .append("，下单时间：").append(pddOrderParam.getOrderCreateTime())
                .append("，服务单类型：").append(pddOrderParam.getServType())
                .append("，商家id：").append(pddOrderParam.getMallId())
                .append("，商品类目名称：").append(pddOrderParam.getCategoryName())
                .append("，商品名称：").append(pddOrderParam.getGoodsName())
                .append("，Sku名称：").append(pddOrderParam.getSkuName());
        //灯的扩展信息
        LampAttribute attribute = JSONObject.parseObject(pddOrderParam.getAttributes(), LampAttribute.class);
        if (Objects.nonNull(attribute)){
            logBuilder.append("，扩展信息-商品属性信息：{灯具形状：").append(attribute.getShape())
                    .append("，灯罩材质：").append(attribute.getMaterial())
                    .append("，吊灯类型：").append(attribute.getChandelierType())
                    .append("，高度：").append(attribute.getHeight())
                    .append("，长度：").append(attribute.getLength())
                    .append("，灯头数：").append(attribute.getLampHolderNum())
                    .append("，灯盏数：").append(attribute.getLampCalyxNum())
                    .append("，图片：<ul class=\"container-images\" id=\"skuImg\"><li><img src=\"")
                    .append(attribute.getSkuImg()).append("\"></li></ul>}");
        }
        // 渠道信息
        zmnOrder.setOuterId(pddOrderParam.getServOrderSn());
        // 客户信息
        ContactInfo contactInfo = pddOrderParam.getContactInfo();
        zmnOrder.setContactName(contactInfo.getContactName());
        zmnOrder.setTelephone(contactInfo.getMobile());
        zmnOrder.setTelephone2(contactInfo.getTelephone());
        zmnOrder.setRemark(StringUtils.isNotBlank(pddOrderParam.getRemark()) ? pddOrderParam.getRemark() : "");
        // 产品信息
        OrderProductDTO orderProduct = new OrderProductDTO();

        ResponseDTO<List<ProductBaseDRO>> servProductListResponseDTO = channelProductThirdListRemoteService.listByChannelIdAndProductParentIdAndSubId(PinDuoDuoConsts.PDD_CHANNEL_ID,
                String.valueOf(pddOrderParam.getCategoryId()), null);

        log.info("【{}】 #ChannelProductMapListRemoteService#listByChannelIdAndProductParentIdAndProductSubId# 入参【{}】【{}】，出参【{}】",
                PinDuoDuoConsts.CHANNEL_NAME, PinDuoDuoConsts.PDD_CHANNEL_ID, pddOrderParam.getCategoryId(), servProductListResponseDTO.toString());

        if (!servProductListResponseDTO.isSuccess() || Objects.isNull(servProductListResponseDTO.getData()) ||
                servProductListResponseDTO.getData().isEmpty()) {
            orderProduct.setProductId(PinDuoDuoMapper.getProductId(pddOrderParam.getCategoryId()));
        } else {
            orderProduct.setProductId(servProductListResponseDTO.getData().get(0).getProductId());
        }

        orderProduct.setNumber(pddOrderParam.getGoodsNum());
        zmnOrder.setOrderProductList(Arrays.asList(orderProduct));
        // 地址信息
        zmnOrder.setAddress(contactInfo.getAddrDetail());
        zmnOrder.setStreet("");
        String addressStr = String.format("%s%s%s%s", contactInfo.getProvName(), contactInfo.getCityName(),
                contactInfo.getDistrictName(), contactInfo.getAddrDetail());
        logBuilder.append("，客户地址：").append(addressStr);
        zmnOrder.setAddressClues(addressStr);
        LngLatLocation location = baiduMapBService.location(addressStr);
        if (location != null) {
            zmnOrder.setLatitude(Double.valueOf(location.getLat()));
            zmnOrder.setLongitude(Double.valueOf(location.getLng()));
            logBuilder.append("，经纬度：").append(location.getLng()).append(",").append(location.getLat());
        }
        // 其他信息
        zmnOrder.setPlat(GlobalConsts.PLAT_MARK_YEYX);
        zmnOrder.setFactory(com.zmn.consts.GlobalConsts.YES);
        zmnOrder.setBizType(com.zmn.consts.GlobalConsts.BIZ_TYPE_F);
        zmnOrder.setGender(GlobalDict.GENDER_NO);
        zmnOrder.setDisableDiscard(GlobalConsts.NO);
        zmnOrder.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        zmnOrder.setInputType(OrderConsts.ORDER_INPUT_TYPE_API);
        zmnOrder.setOperatorLogRemark(logBuilder.toString());

        return zmnOrder;
    }

    /**
     * 用户已签收发起自动跟单
     * @param orderWork
     */
    private void autoOrderTrack(OrderWork orderWork) {

        //查询是否存在用户签收跟单 && 跟单未完成
        OrderTrackQuery query = new OrderTrackQuery();
        query.setOrderId(orderWork.getOrderId());
        query.setWorkId(orderWork.getWorkId());
        query.setMapId(OrderConsts.ORDER_TRACT_PDD_TYPE_ID);
        query.setComplete(GlobalConsts.NO);
        Integer orderTrackCount = orderTrackBService.countByQuery(query);
        log.info("#api#orderTrackCount 查询跟单是否完成：【{}】", JSON.toJSONString(orderTrackCount));
        // 有进行中的跟单则不创建跟单
        if (orderTrackCount != null && orderTrackCount > 0) {
            return;
        }

        //查询指定的跟单信息
        /*List<OrderTrackVO> trackTypeList = Lists.newArrayList();
        DocumentaryContentDIO documentaryContentDIO = new DocumentaryContentDIO();
        documentaryContentDIO.setBizType(orderWork.getBizType());
        documentaryContentDIO.setStatus(GlobalConsts.YES);
        documentaryContentDIO.setId(OrderConsts.ORDER_TRACT_PDD_TYPE_ID);
        log.info("#api#track 查询跟单项目入参：【{}】", JSON.toJSONString(documentaryContentDIO));
        ResponseDTO<List<DocumentaryContentDRO>> responseDTO = documentaryContentListRemoteService.listByQuery(documentaryContentDIO);
        log.info("#api#track 查询跟单项目出参：【{}】", JSON.toJSONString(responseDTO));

        if (!responseDTO.isSuccess() || CollectionUtils.isEmpty(responseDTO.getData())) {
            log.info("#api#trackTypeList 查询跟单项失败或为空，不处理--------");
            return;
        }

        responseDTO.getData().forEach(e -> {
            // 默认跟单等级为一级
            OrderTrackVO orderTrackVO = OrderTrackVO.builder().mapId(e.getId()).mapName(e.getContent()).level(OrderConsts.ORDER_TRACT_OTHER_TYPE_LEVEL).build();
            trackTypeList.add(orderTrackVO);
        });

        // 保存跟单信息
        OrderTrackDTO orderTrackDTO = new OrderTrackDTO();
        orderTrackDTO.setComplete(GlobalConsts.NO);
        orderTrackDTO.setOrderId(orderWork.getOrderId());
        orderTrackDTO.setWorkId(orderWork.getWorkId());
        orderTrackDTO.setOperator("系统");
        orderTrackDTO.setOperatorId((long) orderWork.getChannelId());
        orderTrackDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_CHANNEL);

        List<OrderTrackDetailDTO> detailDTOList = new ArrayList<>(trackTypeList.size());
        orderTrackDTO.setDetailDTOList(detailDTOList);

        trackTypeList.forEach(workTrackDTO -> {

            // 添加到跟单列表
            OrderTrackDetailDTO orderTrackDetailDTO = new OrderTrackDetailDTO();
            orderTrackDetailDTO.setMapId(workTrackDTO.getMapId());
            orderTrackDetailDTO.setMapName(workTrackDTO.getMapName());
            orderTrackDetailDTO.setRemark(workTrackDTO.getRemark());
            orderTrackDetailDTO.setLevel(workTrackDTO.getLevel());
            detailDTOList.add(orderTrackDetailDTO);
        });

        // 保存
        orderTrackBService.updateTrack(orderTrackDTO);*/
    }
}
